import React from 'react';
import {Table, Field, Input, Select, Form, Box, Button, Card, DatePicker, Message, Radio, Collapse,Upload, Switch, Dialog, Grid } from '@alifd/next';
import styles from './index.module.scss';
import {optionChapterList} from '@/api/CourseChapterAPI'
import {detailV, update} from '@/api/CourseQuestionAPI'
import {upLoadImage} from '@/api/CommonAPI'
import {hanlderOption, getOptionValue, getOptionModel, removeItemById} from '@/utils/tool'
const {Row, Col} = Grid;
const FormItem = Form.Item;
const Panel = Collapse.Panel;
const formItemLayout = {
  colSpan: 12,
};

const formItemLayout_two = {
    colSpan: 6,
};
const formItemLayout_three = {
    colSpan: 4,
};

const DEFAULT_DATA = {
    id: '',
    type:'0',
    typeName:'0',
    courseId:'',
    courseCode:'',
    courseSmallName:'',
    chapterId: '',
    chapterCode: '',
    chapterSmallName:'',
    main:'',
    answer:'',
    options:[],
    sort:'',
    state: '0',
    publishTime:'',
    createTime: '',
    createId: '',
    createName: '',
    updateTime: '',
    updateId: '',
    updateName: '',
    mainImage: [],
    answerImage: [],

  };

class DetailCourseQuestion extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            postData: DEFAULT_DATA,
            visible: false,
            stateV:'',
            chapterV: '',
            courseOptionList: [],
            chapterOptionList:[],
            chapterData:[],
            typeOptionList: [],
            stateOptionList: [],
            choiceData: [],
        };
        this.field = new Field(this, {
            parseName: true,
            values: {
                name:[''].map(i => {
                    return { input: i };
                })
            }
        });
    }

    
    // 初始化方法
    componentDidMount(){
        this.props.onRef(this)
    };

    // 1 打开弹框
    onOpen = (key, courseOption, questionTypesData, questionStatesData) => {
        this.resetForm(); 
        detailV(key).then((data)=>{
            if(data){
                // 遍历赋值
                for(var k in data){
                    DEFAULT_DATA[k] = data[k]
                }
                // 处理图片预览
                data.mainImage.map((item)=>{
                    item.state = 'done'
                    item.uid = item.id
                })
                data.answerImage.map((item)=>{
                    item.state = 'done'
                })
                DEFAULT_DATA.type = String(data.type);
                for(const i in questionStatesData){
                    const state = questionStatesData[i]
                    if(state.value == String(data.state)){
                        this.state.stateV = state.label
                        break
                    }
                }
                let choiceOptions = data.options;
                let choiceD = []
                if(choiceOptions && choiceOptions.length > 0){
                    choiceD = choiceOptions.map(i => {
                        return { input: i };
                    })
                    this.field = new Field(this,{
                        parseName: true,
                        values:{name:choiceD}
                    })
                }
                DEFAULT_DATA.chapterId = data.chapterId
                // 调用章节列表接口
                const courseId = data.courseId;
                optionChapterList(courseId).then((arr)=>{
                    let oList = hanlderOption(arr);
                    if(oList){
                        const v = getOptionValue(oList, data.chapterId)
                        console.log('++++++++++++++++++++++++++', v)
                        console.log('choiceD', choiceD)
                        console.log('courseOption', courseOption)
                        console.log('oList', oList)
                        console.log('questionTypesData', questionTypesData)
                        console.log('questionStatesData', questionStatesData)
                        this.setState({
                            courseOptionList: courseOption,
                            chapterOptionList: oList,
                            chapterV: v,
                            typeOptionList: questionTypesData,
                            stateOptionList: questionStatesData,
                            choiceData: choiceD,
                            postData: DEFAULT_DATA,
                            visible: true,
                        })
                    }
                })
            }else{
                Message.error("加载数据失败")
            }
        });
    };
    // 2 关闭弹框
    onClose = () => {
        this.setState({
            visible: false
        })
    };
    // 3 修改表单信息
    formChange = values => {
        console.log('表单改变了:::', values)
        this.setState({
            postData: values
        })
    };
    // 7 改变表单--排序
    changeFormSort= (v) => {
        console.log('排序:', v)
        DEFAULT_DATA.sort = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };
    // 8 改变表单--题干
    changeFormMain= (v) => {
        console.log('题干:', v)
        DEFAULT_DATA.main = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };
    // 8 改变表单--答案
    changeFormAnswer= (v) => {
        console.log('答案:', v)
        DEFAULT_DATA.answer = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };
    // 8 改变表单--备注
    changeFormRemark= (v) => {
        console.log('备注:', v)
        DEFAULT_DATA.remark = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };
    // 删除图片信息
    onRemoveImage =(filename, info) =>{
        console.log('onRemoveImage info is:::', info)
        console.log('onRemoveImage filename is:::', filename)
    }
    // 删除图片信息
    onRemoveMainImage =(info) =>{
        console.log('onRemoveImage info is:::', info)
    }
    /**
     * 重置表单
     */
    resetForm = ()=>{
        DEFAULT_DATA.id = '',
        DEFAULT_DATA.type ='0',
        DEFAULT_DATA.typeName ='0',
        DEFAULT_DATA.courseId ='',
        DEFAULT_DATA.courseCode ='',
        DEFAULT_DATA.courseSmallName ='',
        DEFAULT_DATA.chapterId = '',
        DEFAULT_DATA.chapterCode = '',
        DEFAULT_DATA.chapterSmallName ='',
        DEFAULT_DATA.main ='',
        DEFAULT_DATA.answer ='',
        DEFAULT_DATA.options =[],
        DEFAULT_DATA.sort ='',
        DEFAULT_DATA.state = '0',
        DEFAULT_DATA.publishTime ='',
        DEFAULT_DATA.createTime = '',
        DEFAULT_DATA.createId = '',
        DEFAULT_DATA.createName = '',
        DEFAULT_DATA.updateTime = '',
        DEFAULT_DATA.updateId = '',
        DEFAULT_DATA.updateName = '',
        DEFAULT_DATA.mainImage = [],
        DEFAULT_DATA.answerImage = [],
        this.setState({
            DEFAULT_DATA,
        })
    }

    onPreview(info){
        console.log('onPreview:::', info);
    }
    /************************* 选择列表信息项 start ******************************** */
    getChoiceOptionsValues = () => {
        const zheDieValues = this.field.getValue('name');
        console.log('zheDieValues:::', zheDieValues);
    }
    // 新增选择列表信息项
    addItem(index){
        this.field.addArrayValue('name', index,{input: ''});
    }
    // 移除选择列表信息项
    removeItem(index) {
        console.log('删除了：：', index)
        this.field.deleteArrayValue('name',index);
    }
    // 构建
    input = (value, index) => <Input style={{width:'800px'}} {...this.field.init(`name.${index}.input`)} disabled/>;

    /************************* 选择列表信息项 end ******************************** */
    render(){
        const xDataSource = this.field.getValue('name');
        return (
            <div > 
                <Dialog title="修改题目信息" visible={this.state.visible} footer ={false}  onClose={this.onClose} style={{width: '40%'}} >
                    <Card free className={styles.TwoColumnForm}>
                    <Card.Content>
                        <Form responsive fullWidth value={this.state.postData} labelAlign="top">
                            <FormItem {...formItemLayout_two} label="课程"  required requiredMessage="必填">
                                <Select name='courseId' placeholder="选择课程" dataSource= {this.state.courseOptionList || []}  disabled />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="章节" required requiredMessage="必填">
                                <Select name='chapterId' placeholder="请选择章节" value={this.state.chapterV} dataSource= {this.state.chapterOptionList || []} disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="题目类型"  required requiredMessage="必填">
                                <Select name='type' placeholder="请选择题目类型" dataSource= {this.state.typeOptionList || []} disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="排序" required requiredMessage="必填">
                                <Input placeholder="请输入课程排序" name="sort" onChange={this.changeFormSort} disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout} label="题干" required requiredMessage="必填">
                                <Input.TextArea placeholder="请输入题目主干信息" name="main" onChange={this.changeFormMain} autoHeight={{ minRows: 2, maxRows: 9 }} disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout} label="选择题-选项列表">
                                <Collapse>
                                <Panel title="折叠选择项">
                                    <Table size='small' dataSource={xDataSource} disabled>
                                        <Table.Column title="选择项内容" dataIndex="id" cell={this.input} />
                                    </Table>
                                    </Panel>
                                </Collapse>
                            </FormItem>
                            <FormItem {...formItemLayout} label="答案" required requiredMessage="必填" >
                                <Input.TextArea placeholder="请输入题目答案信息" name="answer"  onChange={this.changeFormAnswer} autoHeight={{ minRows: 2, maxRows: 15 }} disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="上传题干图片：">
                                <Upload.Card name="mainImage" listType="card"
                                    accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp"
                                    request={this.upLoadImageBegin}
                                    onRemove={this.onRemoveMainImage}
                                    defaultValue={this.state.mainImage}
                                    onPreview={this.onPreview}
                                    limit={2}
                                    disabled
                                />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="上传答案图片：">
                                <Upload.Card name="answerImage" listType="card"
                                    accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp"
                                    request={this.upLoadImageBegin}
                                    onRemove={this.onRemoveImage}
                                    defaultValue={this.state.answerImage}
                                    limit={2} disabled
                                />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="状态" required requiredMessage="必填">
                                <Input value={this.state.stateV}  disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="发布时间">
                                <Input name="publishTime" disabled/>
                            </FormItem>

                            <FormItem {...formItemLayout} label="备注">
                                <Input.TextArea placeholder="请输入备注" name="remark" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="创建人">
                                <Input name="createName" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="创建时间">
                                <Input name="createTime" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="最后一次修改人">
                                <Input name="updateName" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="最后一次时间">
                                <Input name="updateTime" disabled/>
                            </FormItem>

                            {/* <FormItem colSpan={12} style={{marginLeft:'35%'}}>
                                <Box spacing={8} direction="row" align="center">
                                    <Form.Submit type="primary" onClick={this.onSubmit} validate>提交</Form.Submit>
                                    <Button onClick={this.onClose} type="secondary">取消</Button>
                                </Box>
                            </FormItem> */}
                        </Form>
                    </Card.Content>
                    </Card>
                </Dialog>
            </div>
        );
    }
}
export default DetailCourseQuestion;

